package com.dream.wukong.common.core.importexport.excel;

import com.dream.wukong.common.core.importexport.csv.Converter;
import com.dream.wukong.common.core.importexport.csv.config.CsvTable;
import com.dream.wukong.common.core.importexport.csv.impl.CsvExportImpl;
import com.dream.wukong.common.core.importexport.csv.parser.AbstractParser;
import com.dream.wukong.common.core.util.DateUtils;
import com.dream.wukong.common.core.util.StringUtil;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: wuyichao
 * @Description:
 * @Date: Created in 9:56 2018/9/19.
 * @Modified:
 */
@Component("excleExport")
public class ExcleExportImpl extends CsvExportImpl implements ExcleExport{
    AbstractParser parser = new ExcelWriter();

    public AbstractParser getParser() {
        return parser;
    }

    public void setParser(AbstractParser parser) {
        super.setParser(parser);
    }
    /**
     * 导出时使用
     * @param data
     *            必须是map或者JAVABEAN
     * @param fields
     *            必须是map的key值或者JAVABEAN属性
     * @return
     */
    @Override
    protected Object[] getRow(Object data, List<? extends CsvTable.CsvField> fields) {
        List<Object> row = new ArrayList<Object>(fields.size());
        for (CsvTable.CsvField csvField : fields) {
            String type = csvField.getType();
            String format = csvField.getFormat();
            Object val = getProperty(data, csvField.getName());


            // 日期格式转化
            if (CsvTable.DATE.equals(type)) {
                val = DateUtils.format((Date) val, CsvTable.DATE_FORMAT);
            }

            if (CsvTable.DATE_TIME.equals(type)) {
                val = DateUtils.format((Date) val, CsvTable.DATE_TIME_FORMAT);
            }

            // 数字格式转化
            if (CsvTable.NUMBER.equals(type)) {
                if (!StringUtil.isNullOrBlank(format)) {
                    DecimalFormat df1 = new DecimalFormat(format);
                    val = df1.format(val);
                }
            }
            // 自定义转化
            if (CsvTable.CUSTOM.equals(type)) {
                if (!StringUtil.isNullOrBlank(format)) {
                    if(format.indexOf(METHOD_NAME_SPLIT) != -1) {
                        val = invokeMethod(format,  val  );
                    }else {
                        Converter convert = getConverter(format);
                        if (convert != null) {
                            val = convert.convert(val);
                        }
                    }
                }
            }
            row.add(val);
        }
        return row.toArray();
    }

}
